package com.zreal.generator.codegenerate.generate;

import com.zreal.generator.config.CodeProperties;
import com.zreal.generator.config.PropertiesBuilder;
import com.zreal.generator.util.Constants;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

public class CodeFactory {
	
	public void outputFile(File templateFile,String outFilePath, Map<String, Object> data) throws Exception {
		CodeProperties properties = PropertiesBuilder.build();
        Configuration cfg = new Configuration();
		cfg.setClassForTemplateLoading(this.getClass(),"/templates/" + properties.getTemplateDir());
	    cfg.setLocale(Locale.CHINA);
	    cfg.setDefaultEncoding(Constants.CHARSET);
	    Template template = cfg.getTemplate(templateFile.getName());
		File dirFile = new File(new File(outFilePath).getParent());
	    if(!dirFile.exists()){
	        if(!dirFile.isDirectory()){
	            dirFile.mkdirs();
	        }
	    }
	    Writer out = new OutputStreamWriter(new FileOutputStream(outFilePath), Constants.CHARSET);
	    template.process(data, out);
	    out.close();
	}
	
}
